<!--- -------------------------------------------------------------------------
CF Component for XML to Struct Parsing 
-------------------------------------------------------------------------- --->

<cfcomponent displayname="XML2struct" hint="Includes recursive functions for parsing XML returned from the back office system">
	<cffunction name="getXML2struct" displayname="Convert XML to Struct" output="no">
		<!--- Arguments And Variables  --->
		<cfargument name="xml_data" type="any" required="yes" >
		<cfargument name="arraylist" type="string" default="">
		
		<cfset var x = 0>
		<cfset var y = "">
		<cfset var m = 0>
		<cfset var n = "">
		<cfset var temp = "">
		<cfset var returnVar = structNew()>
		
		<!--- Function Body --->
		<cfloop from="1" to="#arraylen(arguments.xml_data)#" index="x">
	
			<!--- For a complex (nested) xml structure, Recursively call itself to get to the deepest layer --->
			<cfif structkeyexists(arguments.xml_data[x],"xmlchildren") and arraylen(arguments.xml_data[x].xmlchildren)>
			
				<cfset returnVar[ arguments.xml_data[x].XmlName ] = getXML2struct(arguments.xml_data[x].xmlchildren,arguments.arraylist)>
					
				<!--- Create any arrays specified in calling list (arraylist parameter) --->
				<cfif len(arguments.arraylist)>
					<cfloop list="#arguments.arraylist#" index="m">
						<cfif arguments.xml_data[x].XmlName eq listfirst(m,".")>
							<cfset returnVar[ listfirst(m,".")][listlast(m,".")] = arraynew(1)>
							<!---	go through the number of elements in the MX struct, recursively call xml_to_struct for each element, assign results back to array --->
							<cfloop from="1" to="#arraylen(arguments.xml_data[x].xmlchildren)#" index="n">
								<!--- <cfif listlast(m,".") eq 'suborder'><cfdump var="#arguments.xml_data[x]#"></cfif> --->
								<cfif structkeyexists(arguments.xml_data[x].xmlchildren[n],"xmlchildren")>
									<cfif findnocase(listlast(m,"."),arguments.xml_data[x].xmlchildren[n].xmlname)>
										<cfif arraylen(arguments.xml_data[x].xmlchildren[n].xmlchildren)>
										  <cfset y = getXML2struct(arguments.xml_data[x].xmlchildren[n].xmlchildren,arguments.arraylist)>
										<cfelse>
											<cfset y = arguments.xml_data[x].xmlchildren[n].xmltext>
										</cfif>
										<cfset temp = arrayappend(returnVar[ listfirst(m,".") ][ listlast(m,".")], y ) >
									</cfif>
								</cfif>
							</cfloop>
						</cfif>
					</cfloop>
				</cfif>
				
			<cfelse>
				<cfset returnVar[ arguments.xml_data[x].XmlName ] = arguments.xml_data[x].xmltext>
			</cfif>
		</cfloop>
		<!--- Cropped Get Jurisdiction Only Section because it is logically impossible to fire --->
		<cfreturn returnVar>
	</cffunction>	
		
</cfcomponent>

